package com.stpass.fill_pdf_utf8;

import java.io.FileInputStream;
import java.util.Map;

import com.itext5.xfdfReader.XfdfReader;

public class Main {

	public static void main(String[] args) {
		try {
			Config config = parseArgs(args);
			XfdfReader xfdf = new XfdfReader(config.getFormInputStream());
			Map<String, String> xMap = xfdf.getFields();
			FillPdfForm fillPdfForm = new FillPdfForm(config,xMap);
			fillPdfForm.xfdfFillPdf();
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("See README for more information.");
			System.exit(1);
		}
	}

	private static Config parseArgs(String[] args) throws Exception {
		if (args.length == 0) {
			throw new RuntimeException("Missing arguments.");
		}
		Config config = new Config();
		//String basePath = config.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
		//config.fontPath = basePath.substring(0,basePath.lastIndexOf("/"))+"/simfang.ttf";
		config.setPdfInputStream(new FileInputStream(args[0]));
		config.setPdfOutputStream(System.out);
		config.setFormInputStream(null);
		config.setStampFilename("");
		config.setBackgroundFilename("");
		config.setFlatten(false);
		for (int i = 1; i < args.length; i++) {
			if ("stamp".equals(args[i])) {
				i++;
				config.setStampFilename(args[i]);
			} else if ("background".equals(args[i])) {
				i++;
				config.setBackgroundFilename(args[i]);
			} else if ("fontPath".equals(args[i])) {
				i++;
				config.setFontPath(args[i]);
			} else if ("fontSize".equals(args[i])) {
				i++;
				config.setFontSize(Float.valueOf(args[i]));
			} else if ("fill_form".equals(args[i])) {
				config.setFormInputStream(System.in);
				i++;
				if (!"-".equals(args[i])) {
					throw new RuntimeException("Missing \"-\" after fill_form operation.");
				}
			} else if ("output".equals(args[i])) {
				i++;
				if (!"-".equals(args[i])) {
					throw new RuntimeException("Missing \"-\" after output operation.");
				}
			} else if ("flatten".equals(args[i])) {
				config.setFlatten(true);
			} else {
				throw new RuntimeException("Unknown operation: " + args[i]);
			}
		}
		return config;
	}

}
